package web.jsoft.com;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

@ManagedBean
@RequestScoped
public class LoginBean {

    private AuthenticationManager authenticationManager;
    private String userName;
    private String password;  

    public void setAuthenticationManager(AuthenticationManager authenticationManager){
    	this.authenticationManager = authenticationManager;
    }
    
    public AuthenticationManager getAuthenticationManager(){
    	return this.authenticationManager;
    }
    
    public String login() {
        try {
            Authentication request = new UsernamePasswordAuthenticationToken(this.getUserName(), getPassword());
            Authentication result = authenticationManager.authenticate(request);
            SecurityContextHolder.getContext().setAuthentication(result);

        } catch (AuthenticationException e) {
            String loginFailedMessage = FacesUtils.getBundleKey("msg", "login.failed");
            FacesUtils.addErrorMessage(loginFailedMessage);
            return null;
        }
        return "/ui/welcome.jsf";
    }
   
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
